﻿using HCore;

namespace MEat
{
    public partial class MEatGame
    {
        private class ClientGlobalState : State<MEatGame>
        {
            private int _lastSendRttFrameCount;
            public ClientGlobalState(MEatGame owner) : base(owner)
            {
            }

            public override void Enter()
            {
                _owner.Log("Enter ClientGlobalState");
                _lastSendRttFrameCount = -1;
                _owner.networkMgr.Register(PacketType.RTT, RTTHandle);
            }

            private void RTTHandle(InputMemoryBitStream input)
            {
                Fix sendRttTime = new Fix(input.ReadInt());
                int frameCount = input.ReadInt();
                Fix now = _owner.timer.totalTime;
                _owner.Log("frameCount: " + frameCount + " Rtt: " + (int) ((now - sendRttTime) * 1000) + "ms");
            }

            public override void Execute()
            {
                if (_owner.networkMgr.connected &&
                    _owner._inBattle 
                    && _owner.timer.frameCount % _owner.timer.frameRate == 0 
                    && _owner.timer.frameCount > _lastSendRttFrameCount)
                {
                    _lastSendRttFrameCount = _owner.timer.frameCount;
                    OutputMemeryBitStream output = new OutputMemeryBitStream();
                    output.WriteByte(PacketType.RTT);
                    output.WriteInt(_owner.timer.totalTime.Raw);
                    output.WriteInt(_owner.timer.frameCount);
                    _owner.networkMgr.Send(output.GetBuffer(), output.GetByteLength());
                }
            }

            public override void Exit()
            {
                _owner.networkMgr.Unregister(PacketType.RTT);
                _owner.Log("Exit ClientGlobalState");
            }
        }
    }
}